from flask import Flask, render_template, jsonify, request
import numpy as np
import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import io
import base64
from matplotlib.colors import ListedColormap
import json

app = Flask(__name__)

# 全局变量存储数据
iris = load_iris()
X = iris.data[:, :2]  # 只使用前两个特征
y = iris.target
feature_names = iris.feature_names[:2]
target_names = iris.target_names

# 划分数据集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

def get_knn_accuracy(k):
    """计算给定K值的准确率"""
    model = KNeighborsClassifier(n_neighbors=k)
    model.fit(X_train, y_train)
    y_pred = model.predict(X_test)
    return accuracy_score(y_test, y_pred)

def generate_decision_boundary(k):
    """生成决策边界图"""
    plt.figure(figsize=(10, 8))
    
    # 训练模型
    model = KNeighborsClassifier(n_neighbors=k)
    model.fit(X_train, y_train)
    
    # 创建网格
    h = 0.02
    x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                         np.arange(y_min, y_max, h))
    
    # 预测网格点
    Z = model.predict(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)
    
    # 绘制决策边界
    cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF'])
    cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF'])
    
    plt.pcolormesh(xx, yy, Z, cmap=cmap_light, alpha=0.8)
    
    # 绘制训练数据
   